﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
/**
 * ApmetrixServerUtilities.cs
 * SDK
 * 
 * Created by Jon Holtan on 12/17/12.
 * Copyright (c) 2012-2013 apMetrix. All rights reserved.
**/

namespace Apmetrix
{
    class ApmetrixServerUtilities
    {
        private static readonly string TAG = "Apmetrix SDK / ServerUtilities";
        protected static readonly internal int SC_BAD_REQUEST = 400;
        protected static readonly internal int SC_OK = 200;
        /*
        * Use Http GET method to send url string to API Server
        * Note: Checks response status but does nothing with response entity.
        * 
        * @param url to send
        */
        protected static internal int get(string url)
        {
            int statusCode = 0;

            if (ApmetrixConstants.LOG_DEBUG)
                Console.WriteLine("{0} DEBUG: Sending URL: {1}", TAG, url);

            try
            {
                //send url to server using HTTP GET method
                HttpWebRequest wrGET = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse wrResponse = (HttpWebResponse)wrGET.GetResponse();
                statusCode = (int)wrResponse.StatusCode;
                wrResponse.Close();

                if (statusCode == SC_BAD_REQUEST)
                {
                    Console.WriteLine("{0} ERROR: Gateway rejected gameDataset is invalid", TAG);
                    wrResponse.Close();
                    return statusCode;
                }
                else if (statusCode == ApmetrixConstants.HTTP_SC_IM_A_TEAPOT)
                {
                    Console.WriteLine("{0} ERROR: Gateway rejected gameUnifier is invalid", TAG);
                    wrResponse.Close();
                    return statusCode;
                }
                else if (statusCode != SC_OK)
                    throw new ApmetrixException(TAG, 999, "The gateway returned an invalid response: " + statusCode);
                wrResponse.Close();
            }
            catch (ArgumentNullException e)
            {
                throw new ApmetrixException(TAG, 999, "Null URL: ");
            }
            catch (NotSupportedException e)
            {
                throw new ApmetrixException(TAG, 999, "Functionality Not Supported: Contact Apmetrix");
            }
            catch (System.Security.SecurityException e)
            {
                throw new ApmetrixException(TAG, 999, "Security Error on call");
            }
            catch (UriFormatException e)
            {
                throw new ApmetrixException(TAG, 999, "Invalid URI Format: ");
            }
            catch (InvalidOperationException e)
            {
                throw new ApmetrixException(TAG, 999, "Invalid Operation" + e.Message);

            }



            return statusCode;
        }

        /**
        * Issue a POST request to the server.
        * (Called when registering/unregistering GCM account with API Server)
        *
        * @param endpoint POST address.
        * @param params request parameters.
        * @throws IOException propagated from POST.
        */
        protected static void post(string endpoint, Dictionary<String, String> param)
        {

        }


       /*
        * Use Http GET method to retrieve external IP Address (tested)
        */
        protected static internal string getExtIPAddress()
        {
            string externalIP = "";
            int statusCode = 0;
            Stream wrGetStream = null;
            StreamReader wrGetReader = null;
            try
            {
                //send url to server using HTTP GET method
                HttpWebRequest wrGET = (HttpWebRequest)WebRequest.Create(ApmetrixConstants.EXT_IP_URL);
                HttpWebResponse wrResponse = (HttpWebResponse)wrGET.GetResponse();
                statusCode = (int)wrResponse.StatusCode;

                if (statusCode == SC_OK)
                {
                    wrGetStream = wrGET.GetResponse().GetResponseStream();
                    wrGetReader = new StreamReader(wrGetStream);
                    while (!wrGetReader.EndOfStream)
                        externalIP = wrGetReader.ReadLine();
                    if (ApmetrixConstants.LOG_DEBUG)
                        Console.WriteLine("{0} DEBUG: Ext IP Address = {1} ", TAG, externalIP);

                }
                else
                    Console.WriteLine("{0} ERROR: When getting External IP, invalid response status {1}", TAG, statusCode);
            }
            catch (InvalidOperationException e)
            {
                throw new ApmetrixException(TAG, 999, "Invalid Operation" + e.Message);

            }
            finally
            {
                if (ApmetrixConstants.LOG_DEBUG)
                    Console.WriteLine("{0} DEBUG: Finished", TAG);
            }
            return externalIP;
            
        }
    }
}
